package com.cjx.leetcode.backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author cjx
 * @Description E39.组合总和【中】
 * @date 2024/4/2 13:00
 **/
public class E39 {
    private final List<List<Integer>> result = new ArrayList<>();
    private final List<Integer> path = new ArrayList<>();
    private int sum = 0;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(candidates, target, 0);
        return result;
    }

    public void backtracking(int[] candidates, int target, int startIndex) {
        if (sum == target) {
            result.add(new ArrayList<>(path));
            return;
        }

        for (int i = startIndex; i < candidates.length ; i++) {
            int candidate = candidates[i];
            if (sum + candidate > target) {
                break;
            }
            path.add(candidate);
            sum += candidate;
            backtracking(candidates, target, i);
            path.remove(path.size() - 1);
            sum -= candidate;
        }
    }
}

